package com.lhf.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.crypto.SecureUtil;
import com.lhf.aicloud.utils.MinIoUtil;
import com.lhf.aicloud.utils.NameUtil;
import com.lhf.aicloud.utils.ResponseEntity;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author : lhf
 * @date : Created in 2024/07/28
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private MinIoUtil minIoUtil;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     */
    @RequestMapping("/create")
    public ResponseEntity createCaptcha(HttpServletRequest request) {
        String captchaUrl = "";
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        String fileName = NameUtil.getCaptchaName(request);
        try (InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())) {
            // 上传到 minio
            captchaUrl = minIoUtil.upload("captcha/" + fileName, inputStream, "image/png");
            // 将验证码存储到 Redis 中
            redisTemplate.opsForValue().set(fileName, lineCaptcha.getCode(), 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.success(captchaUrl);
    }
}
